package com.ruoyi.merchant.elasticsearch;

import com.ruoyi.common.core.domain.Shop;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.elasticsearch.script.Script;
import org.springframework.data.elasticsearch.core.ElasticsearchAggregations;


import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: ysq
 * @Date: 2024/09/13/11:00
 * @Description: Elasticsearch聚合查询, 查询每种类型的店铺的数量，以及id
 */
@Service
public class PerShopService {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public List<String> performAggregation() {
        // 创建布尔查询构建器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("types", "车辆维修")); // 仍然使用 match 查询

        //创建查询构建器并添加聚合
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).addAggregation(AggregationBuilders.terms("type_aggregation").field("types.keyword"));
        SearchHits<Shop> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), Shop.class, IndexCoordinates.of("new_shop"));
        //检查总命中数
        long totalHits = searchHits.getTotalHits(); // 适用于某些新版本
        System.out.println("Total hits: " + totalHits);
        //解析聚合结果
        List<SearchHit<Shop>> searchHits1 = searchHits.getSearchHits();
        List<String> ids = new ArrayList<>();
        for (SearchHit<Shop> searchHit : searchHits1) {
            ids.add(searchHit.getId());
        }
        System.out.println("ids:"+ids);
        return ids;
    }
}
